package com.etc.controller;

import com.etc.commons.can;
import com.etc.pojo.sysuser.SysUser;
import com.etc.service.SysUserService;
import com.etc.utils.FtpUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;


    @RequestMapping("zhuce")
    public String d() {
        return "zhuce";
    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String upload(SysUser user, HttpServletRequest request, Model model) throws IOException {
        System.out.println(request.getParameter("name"));
        //保存数据库的路径
        String sqlPath = null;
        //定义文件保存的本地路径
        String localPath = "E:\\tmp\\als\\Upload";
        //定义 文件名
        String filename = null;
        if (!user.getFile().isEmpty()) {
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType = user.getFile().getContentType();
            //获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            //得到 文件名
            filename = uuid + "." + suffixName;
            InputStream inputStream = user.getFile().getInputStream();
            FTPClient ftpClient = FtpUtil.getFTPClient(can.FTP_HOST, can.FTP_PORT, can.USER_NAME, can.PASSWORD);
            boolean b = FtpUtil.uploadFile(ftpClient, inputStream, can.FTPPSTH, filename);
            if (b) {
                //把图片的相对路径保存至数据库
                sqlPath = "/img/" + filename;
                if (sqlPath != null) {
                    user.setPortRait("http://192.168.88.28"+sqlPath);
                }
                sysUserService.insert(user);
                model.addAttribute("user", user);
                FtpUtil.closeFTP(ftpClient);
                return "ppp";
            } else {
                return "ppp";
            }
        }
        return "ppp";
    }
}
